package com.qingluan.dd;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.zip.Inflater;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.qingluan.Database.MissionDataBase;
import com.qingluan.Database.Personal_Info_database;
import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.dd.MissionListFullscreenActivity.DragListAdapter;
import com.qingluan.dd.R.id;
import com.qingluan.dd.InetTool.GetTalking;
import com.qingluan.dd.InetTool.GetTalking.setOnPost;
import com.qingluan.server.BackgroundServer;
import com.qingluan.server.BroadCastRecevier;
import com.qingluan.server.BroadCastRecevier.ReceiveListener;
import com.qingluan.widget.DragListView;
import com.qingluan.widget.DragListView.OnRefreshTailListener;
import com.qingluan.widget.TimeHelper;
import com.qingluan.widget.DragListView.OnRefreshListener;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.view.ViewDebug.IntToString;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TalkActivity extends Activity {
	//graph area
	
	private DragListView displayList;
	private EditText myMessage;
	private Button commit_btn;
	private DragListAdapterForTalking ListAdapter;
	//context area
	private Context context_this_activity;
	private IntentFilter filter ;
	
	//my info 
	private String myName;
	private String myEmail;
	private String uid;
	private String mission_id;
	private BroadCastRecevier broadCast;
	private String TAG = TalkActivity.class.getName();
	//sign area
	private boolean ifBuild =  false;
	private boolean ifOpen	=  false;
	private String tag = this.getClass().getName();
	private TalkingBuild onethreadBuild ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_talk);
		
		context_this_activity 
					= getApplicationContext();
		filter		= new IntentFilter();
		filter.addAction(ARGUMENTS.PUSH_SERVICE_NAME);
		broadCast 	= new BroadCastRecevier();
		registerReceiver(broadCast, filter);
		
		
		uid 		= getIntent().getExtras().getString("uid");
		mission_id  = getIntent().getExtras().getString("mission_id");
		
//		inflater  	= (LayoutInflater ) context_this_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		displayList = (DragListView)findViewById(R.id.talk_content_list);
		myMessage 	= (EditText)findViewById(R.id.talk_control_area_edit);	
		commit_btn	= (Button) findViewById(R.id.talk_control_area_commit_btn);
		
		myName 	= new Personal_Info_database(context_this_activity).searchName(uid);
		myEmail = new Personal_Info_database(context_this_activity).searchEmail(uid);
		
		
		ListAdapter = new DragListAdapterForTalking(context_this_activity);
		displayList.setAdapter(ListAdapter);
		OnRefreshListener listener = new RefreshListener(myEmail, mission_id);
		RefreshTailListener tailListener = new RefreshTailListener();
		displayList.setOnRefreshListener(listener);
		displayList.setOnRefreshTailListener(tailListener);
		//start service 
		Log.d("some", "attempted to start service...");
		startService();
		
		//push a extended thread to send log-in info 
		onethreadBuild = new TalkingBuild();
		onethreadBuild.start();
		
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
		}
		return false;
	}
	
	/*
	 * this method is to for turn activity 
	 */
	public void get_partner_location(View view){
		Intent intent = new Intent(TalkActivity.this,MapPartnerLocation.class);
		String attendees   = new MissionDataBase(context_this_activity).search(mission_id,MissionDataBase.MISS_OBJ_ID,MissionDataBase.ATTENDEE );
		Log.d(tag,attendees);
//		Toast.makeText(context_this_activity, attenttee, Toast.LENGTH_SHORT).show();
		intent.putExtra("uid", uid);
		intent.putExtra("mission_id",mission_id);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		
		context_this_activity.startActivity(intent);
	}
	
	public void sendMessage(View view){
		

		commit_btn.setVisibility(View.GONE);
		String content = myMessage.getText().toString();
		if (content.length() <1 ){
			return ;
		}
		JSONObject json = new JSONObject();
		
		//fill in the JSON with some data.
		try {
			
			json.put(GetTalking.oneTalking_talking_email, myEmail);
			json.put(GetTalking.mission_id_J, mission_id);
			json.put(GetTalking.oneTalking_talking_name, myName);
			json.put(GetTalking.oneTalking_talking_content, content);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		GetTalking.TalkingPost( new setOnPost(){

			@Override
			public void OnPostSuccess(String json) {
				// TODO Auto-generated method stub
				Log.d(tag, "send succeff");
				
				commit_btn.setVisibility(View.VISIBLE);
				myMessage.setText("");
			}

			@Override
			public void OnPostFailed(String error) {
				// TODO Auto-generated method stub
				Toast.makeText(context_this_activity, error, Toast.LENGTH_SHORT).show();

				commit_btn.setVisibility(View.VISIBLE);
			}
			
		}, json);
		
		
		
		//getMessage(mission_id, myEmail);
		
		
	}
	
	private void paraInfo(JSONObject info) throws JSONException{
		JSONArray jsonArray = info.getJSONArray("response");
		for (int i=0; i < jsonArray.length() ;i ++){
			JSONObject one = jsonArray.getJSONObject(i);
			OperationOneMessage(one);
		}
	}
	
	private void getMessage(String mission_id, String email){
		
		ArrayList<String > ids 	= ListAdapter.getAllIds();
		JSONArray jsonArray 	= new JSONArray();
		JSONObject jsonObject 	= new JSONObject();
		
		for (String one : ids){
			jsonArray.put(one);
		}
		
		
		try {
			jsonObject.put(GetTalking.talk_ids_J, jsonArray);
			jsonObject.put(GetTalking.mission_id_J, mission_id);
			jsonObject.put(GetTalking.join_email_J, email);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		GetTalking.MessagePullByPost(new setOnPost(){

			@Override
			public void OnPostSuccess(String json) {
				// TODO Auto-generated method stub
				commit_btn.setVisibility(View.VISIBLE);
				
				try {
					
					if (new JSONObject(json).get("response").equals("fail")){
						Toast.makeText(context_this_activity, "arguments error", Toast.LENGTH_SHORT).show();
					}else{
						Log.d(TAG,json);
						paraInfo(new JSONObject(json));
						
						myMessage.setText(null);
					}
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void OnPostFailed(String error) {
				// TODO Auto-generated method stub
				commit_btn.setVisibility(View.VISIBLE);
				Toast.makeText(context_this_activity, error, Toast.LENGTH_SHORT).show();
			}
			
		}, jsonObject);
	}
	
	public void startService(){
//		start service...
		Intent intentService = new Intent(TalkActivity.this,BackgroundServer.class);
		context_this_activity.startService(intentService);
		
		broadCast.setReceiveListenr(new ReceiveListener(){

			@Override
			public void receive(String info) {
				// TODO Auto-generated method stub
//				Log.d(tag, info);
				try {
					JSONObject jsonInformation = new JSONObject(info);
					String status 		= jsonInformation.getString("status");
					if (status.equals("talk")){
						String talk_name 	= jsonInformation.getString("talk_name");
						String talk_content = jsonInformation.getString("talk_content");
						
						HashMap<String, String >oneItem = new HashMap<String, String>();
						oneItem.put(GetTalking.oneTalking_talking_name, talk_name);
						oneItem.put(GetTalking.oneTalking_talking_content, talk_content);
						oneItem.put("time", TimeHelper.GetNowTime());
						ListAdapter.addData(oneItem);
						
//						displayList.requestFocus(direction-1);
						
					}else if (status.equals("add_to_talk_list")){
						Toast.makeText(context_this_activity, "Move to Talking room !", Toast.LENGTH_SHORT).show();
					}else if(status.equals("get_talk")) {
						String talk_name = jsonInformation.getString("talk_name");
						String talk_content = jsonInformation.getString("talk_content");
						String talk_time = TimeHelper.GetNowTime();
						
						HashMap<String, String >oneItem = new HashMap<String, String>();
						oneItem.put(GetTalking.oneTalking_talking_name, talk_name);
						oneItem.put(GetTalking.oneTalking_talking_content, talk_content);
						oneItem.put("time", talk_time);
						ListAdapter.addData(oneItem);
						
						int direction = ListAdapter.getCount();
						displayList.setSelection(direction-1);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				//Toast.makeText(context_this_activity, info, Toast.LENGTH_SHORT).show();
				ifOpen = true;
				Log.d(tag,"tag : ON for ifopen");
			}
			
		});
		
		
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(broadCast);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		onethreadBuild.OFF();
		super.onStop();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		onethreadBuild.OFF();
		super.onPause();
	}
	
	
	private void OperationOneMessage(JSONObject oneMessage) throws JSONException{
		Log.d(TAG,oneMessage.toString());
		String misison_id_M 	= oneMessage.getString(GetTalking.mission_id_J);
		String talking_id 		= oneMessage.getString(GetTalking.oneTalking_talking_id);
		String talking_email 	= oneMessage.getString(GetTalking.oneTalking_talking_email);
		String talking_name 	= oneMessage.getString(GetTalking.oneTalking_talking_name);
		String talking_content  = oneMessage.getString(GetTalking.oneTalking_talking_content);
		
		HashMap<String, String> oneItem = new HashMap<String, String>();
		oneItem.put(GetTalking.mission_id_J, misison_id_M);
		oneItem.put(GetTalking.oneTalking_talking_id,talking_id);
		oneItem.put(GetTalking.oneTalking_talking_email,talking_email);
		oneItem.put(GetTalking.oneTalking_talking_name, talking_name);
		oneItem.put(GetTalking.oneTalking_talking_content,talking_content);
		oneItem.put("time", TimeHelper.paraTimeByLong(System.currentTimeMillis() ));
		ListAdapter.addData(oneItem);
		
	}
	
	private void TalkingBuildMethod(){
		if (! ifBuild ){
			JSONObject jsonMessage = new JSONObject();
			try {
				jsonMessage.put(GetTalking.mission_id_J, mission_id);
				jsonMessage.put(GetTalking.talk_build_email_J,myEmail );
				jsonMessage.put(GetTalking.talk_build_name_J, myName);
				jsonMessage.put(GetTalking.talking_status_J, "log_in");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d("send info", jsonMessage.toString());
			//broadcast ...
			Intent  sendMessageToService =  new Intent();
			sendMessageToService.setAction(ARGUMENTS.SEND_INFO_TO_SERVICE);
			sendMessageToService.putExtra(BroadCastRecevier.KEY, jsonMessage.toString());
			
			sendBroadcast(sendMessageToService);
			ifBuild = true;
		}else {
			return ;
		}
	}
	//#############################################################
	
	
	class DragListAdapterForTalking extends BaseAdapter {
		
		// data area
		private ArrayList<HashMap<String,String>> DATA = new ArrayList<HashMap<String, String>>();
	
		//context area
		private Context context_from;
		
		//view widget area
		private TextView  name;
		private TextView  time;
		private TextView  content;
		
		
		public DragListAdapterForTalking(Context context) {
			// TODO Auto-generated constructor stub
			this.context_from = context;
		}
		
		//foundation methods area
		public void addData(HashMap<String, String> oneItem){
			DATA.add(oneItem);
			notifyDataSetChanged();
		}
		
		public ArrayList<String> getAllIds(){
			ArrayList<String > ids = new ArrayList<String>();
			for (HashMap<String, String> one  : DATA){
				ids.add(one.get(GetTalking.talk_id));
			}
			return ids;
		}
				
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return DATA.size();
		}

		@Override
		public HashMap<String, String> getItem(int position) {
			// TODO Auto-generated method stub
			return DATA.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			LayoutInflater inflater = (LayoutInflater) this.context_from.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.talk_item, null);
			
			//initial my views
			name 	= (TextView)convertView.findViewById(R.id.talk_name);
			time 	= (TextView)convertView.findViewById(R.id.talk_send_time);
			content 	= (TextView)convertView.findViewById(R.id.talk_message);
			
			
			name.setText(DATA.get(position).get(GetTalking.oneTalking_talking_name));
			time.setText(DATA.get(position).get("time"));
			content.setText(DATA.get(position).get(GetTalking.oneTalking_talking_content));
			
			
			
			return convertView;
		}
		
	}
	// implement refresh listener
	class RefreshListener implements OnRefreshListener{
		private String mission_id;
		private String email;
		
		public RefreshListener(String email ,String mission_id){
			this.email 		= email;
			this.mission_id = mission_id; 
		}
		
		@Override
		public int onRefresh() {
			// TODO Auto-generated method stub
			getMessage(mission_id , email);
			
			return 0;
		}
		
	}
	
	class RefreshTailListener implements OnRefreshTailListener{

		@Override
		public int onRefresh() {
			// TODO Auto-generated method stub
			return DragListView.DONE;
		}
		
	}
	
	
	class TalkingBuild extends Thread{
		private int ON = 1;
		private int OFF = -1;
		private int TAG = OFF;
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			int count = 0;
			while (!ifBuild){
				if ( ifOpen ){
					Log.d("SF", "start round do ");
					/*
					 *  send broadcast information ...
					 *  by round-sleep-ask
					 */
					TalkingBuildMethod();
					count ++;
				}
				
				if (ifBuild){
					break;
				}
				try {
					sleep(1000);
					Log.d("SF","Login failed ... sleep 1 s");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (count >25){
					break;
				}
			}
			
			
			try {
				sleep(50);
				this.interrupt();
				Log.d("kill THread", "Kill this thread");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			
		}
		
		
		public void OFF(){
			if (this.isAlive()){
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.d(tag, "stop this thread failed ... check it ");
				}
				
				this.interrupt();
			}
		}
	}
	

	
}
